package com.waves.netty;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

/**
 * 任务计算结果Future
 */
@Slf4j
public class TestFuture {
    @Test
    public void jdkFuture() throws ExecutionException, InterruptedException {
        // 线程池
        ExecutorService service = Executors.newFixedThreadPool(2);
        Future<Integer> future = service.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.debug("进行计算");
                Thread.sleep(1000);
                return 50;
            }
        });

        log.debug("等待结果");
        log.debug("结果是：{}", future.get());
    }
    @Test
    public void nettyFuture() throws ExecutionException, InterruptedException {
        EventLoop eventLoop = new NioEventLoopGroup().next();
        io.netty.util.concurrent.Future<Integer> future = eventLoop.submit(() -> {
            log.debug("进行计算");
            return 70;
        });
        log.debug("等待结果");
        log.debug("结果是：{}", future.get());
    }
    @Test
    public void nettyPromise() throws ExecutionException, InterruptedException {
        // 1. 创建eventLoop对象
        EventLoop eventLoop = new NioEventLoopGroup().next();
        // 2. 创建结果容器
        DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);
        new Thread(() -> {
            log.debug("开始计算");
            try {
                // int i = 1 / 0;
                Thread.sleep(1000);
                // 将thread结果传递给eventLoop
                promise.setSuccess(80);
            } catch (InterruptedException e) {
                e.printStackTrace();
                promise.setFailure(e);
            }
        }).start();
        log.debug("等待结果");
        log.debug("结果是：{}", promise.get());
    }
}
